<?php

namespace App\Http\Resources\Train\TrainOrder;

use App\Trip\Train\TrainPorts;
use App\Trip\Train\TrainType;
use App\Trip\Translate\Niutrans\Translation;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use JsonSerializable;

class TrainOrderTrainResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     *
     * @return array|Arrayable|JsonSerializable
     * @throws Exception
     * @throws GuzzleException
     */
    public function toArray($request)
    {
        $train_info         = parent::toArray($request);
        $train_type_name    = TrainType::getTrainTypeName($train_info['train_code']);
        $train_info['type'] = [
            "name"    => $train_type_name,
            "name_uy" => TrainType::getTrainTypeNameTranslation($train_type_name, 'uy'),
        ];

        $train_info['start_at']    = Carbon::parse($train_info['start_at'])->format("Y-m-d H:i");
        $train_info['arrive_at']   = Carbon::parse($train_info['arrive_at'])->format("Y-m-d H:i");
        $train_info['start_date']  = Carbon::parse($train_info['start_at'])->format("Y-m-d");
        $train_info['arrive_date'] = Carbon::parse($train_info['arrive_at'])->format("Y-m-d");
        $train_info['start_time']  = Carbon::parse($train_info['start_at'])->format("H:i");
        $train_info['arrive_time'] = Carbon::parse($train_info['arrive_at'])->format("H:i");
        if (isset($train_info['train_code']) && isset($train_info['from_station_code'])) {
            $train_info['checking_port'] = TrainPorts::checking($train_info['train_code'], $train_info['from_station_code']);
            try {
                $train_info['checking_port'] = (new Translation($train_info['checking_port']))->translate()->getTranslation();
            } catch (Exception $e) {

            }
        }
        unset(
            $train_info['id'],
            $train_info['user_id'],
            $train_info['order_sn'],
            $train_info['created_at'],
            $train_info['updated_at'],
            $train_info['alternative'],
            $train_info['alternative_seat'],
            $train_info['alternative_price'],
        );
        return $train_info;
    }
}
